<template>
  <div class="login">
    <div class="texture"></div>
    <div class="main">
      <div class="login-inner" v-if="!loginResult">
        <div class="close" @click="close">
          <i></i>
        </div>
        <div class="title">
          <h2>登陆</h2>
        </div>
        <div class="form">
          <div class="form-inner">
            <div class="input">
              <div class="inner">
                <label>
                  <img
                    src="../../../assets/images/form_label_phone.png"
                    style="transform:translateX(3px)"
                    alt="label"
                  >
                </label>
                <input
                  name="手机号"
                  v-validate="'required|digits:11'"
                  type="tel"
                  v-model="formData.phone"
                  @blur="RTverity"
                  placeholder="请输入手机号"
                  @keypress="RTverityInfoPhone=''"
                  @change="RTverityInfoPhone=''"
                >
              </div>
              <span v-if="errors.first('手机号')" class="error-info">
                {{ errors.first('手机号') }}
                <a
                  v-if="RTverityInfoPhone.match(/\u672a\u62a5\u540d/)"
                  style="display:none;margin-left:5px;color:#fe5d73"
                  href="https://mp.weixin.qq.com/s/rPl5oawP1QhqMMLgYSQprw"
                >立即报名</a>
              </span>
            </div>
            <div class="input">
              <div class="inner">
                <label>
                  <img
                    src="../../../assets/images/form_label_id.png"
                    alt="label"
                    style="height:11px"
                  >
                </label>
                <input
                  name="图形验证码"
                  v-validate="'required'"
                  type="text"
                  placeholder="图形验证码"
                  v-model="formData.imgCode"
                >
              </div>
              <div class="imgCode">
                <i :style="{backgroundImage:'url('+imgCode.img+')'}"></i>
              </div>
              <span
                v-if="RTverityInfoImgCode||errors.first('图形验证码')"
                class="error-info"
              >{{ RTverityInfoImgCode||errors.first('图形验证码') }}</span>
            </div>
            <div class="input">
              <div class="inner">
                <label>
                  <img src="../../../assets/images/form_label_license.png" style="height:11px">
                </label>
                <input
                  name="验证码"
                  v-validate="'required|numeric'"
                  type="tel"
                  placeholder="短信验证码"
                  @blur="RTverity"
                  v-model="formData.phoneCode"
                >
              </div>
              <div :class="['sender',senderAble?'':'disable']" @click="verityImgCode">
                <span>{{getCodeCounter||senderInfo}}</span>
              </div>
              <span
                v-if="errors.first('验证码')||RTverityInfoCoder"
                class="error-info"
              >{{ RTverityInfoCoder||errors.first('验证码') }}</span>
            </div>
          </div>
        </div>
        <div class="formButton">
          <div class="submit act" @click.stop="submit">
            <span>立即登陆</span>
          </div>
          <div class="subInfo">
            <span>注：请使用金犊奖报名手机号登录</span>
          </div>
        </div>
      </div>
      <div class="tips" v-if="loginResult">
        <div class="info">
          <span v-if="loginResult==='field'">抱歉！您还未报名该活动</span>
          <span v-if="loginResult==='overdue'">抱歉！该活动已结束</span>
        </div>
        <div class="button" @click="close">
          <span>知道了</span>
        </div>
      </div>
    </div>
    <div :class="['pop',popState?'act':'']">
      <span>抱歉，您还未报名该活动</span>
      <br>
      <span>即将为您跳转活动介绍页面哦～</span>
    </div>
  </div>
</template>

<script>
import store from "../../../store.js";
import axios from "axios";
axios.defaults.withCredentials = true;
export default {
  data() {
    return {
      dev: false,
      senderInfo: "获取验证码",
      senderAble: true,
      RTverityInfoPhone: "",
      RTverityInfoCoder: "",
      RTverityInfoImgCode: "",
      getCodeCounter: null,
      imgCode: {
        img: "static/images/jdj_login_imgCode.jpg",
        code: "m8k2"
      },
      formData: {
        phone: "",
        imgCode: "",
        phoneCode: ""
      },
      loginResult: "",
      popState: false
    };
  },
  computed: {
    serveAPI: {
      get() {
        let serve = {};
        let portAddress = store.state.apiPort.map(
          e => store.state.apiOrigin + e.split(":")[1]
        );
        let portName = store.state.apiPort.map(e => e.split(":")[0]);
        for (let i = 0; i < portName.length; i++) {
          serve[portName[i]] = portAddress[i];
        }
        return serve;
      },
      set() {}
    }
  },
  methods: {
    //----------------------------------------------------
    // default
    init() {
      this.getImgCode();
    },
    close() {
      store.commit("upload", { prope: "loginState", data: false });
      this.loginResult = "";
    },
    cleanState() {
      window.scrollTo(0, 0);
      let inputList = [...document.querySelectorAll("input")];
      inputList.map(e => {
        e.blur();
      });
    },
    //----------------------------------------------------
    // verity
    RTverity(e) {
      if (this.dev) return;
      this.$validator.validate(e.target.name).then(result => {
        if (result) {
          if (e.target.name === "手机号") this.verityPhone();
          if (e.target.name === "验证码") {
            this.$validator.validate("手机号").then(result => {
              if (result && !this.RTverityInfoPhone) {
                this.verityCode();
              }
            });
          }
        }
      });
    },

    verityPhone() {
      this.$validator.validate("手机号").then(result => {
        if (result) {
          axios
            .get(this.serveAPI.verityPhone + this.formData.phone)
            .then(res => {
              // console.log(res);
              if (res.data.error) {
                this.RTverityInfoPhone = res.data.error;
                // alert(res.data.error)
                setTimeout(() => {
                  if (this.RTverityInfoPhone.match(/\u672a\u62a5\u540d/)) {
                    // alert('即将为您跳转活动介绍页~')
                    this.cleanState();
                    this.popState = true;
                    setTimeout(() => {
                      location.replace(
                        "https://mp.weixin.qq.com/s/rPl5oawP1QhqMMLgYSQprw"
                      );
                    }, 2000);
                  }
                }, 500);
              }
            });
          // this.verityImgCode();
        }
      });
    },

    verityImgCode() {
      if (!this.senderAble || this.RTverityInfoPhone) return;
      this.$validator.validate("图形验证码").then(result => {
        if (result) {
          axios
            .post(this.serveAPI.verityImgCode, {
              mobileNumber: this.formData.phone,
              captcha: this.formData.imgCode
            })
            .then(res => {
              if (res.data.Response.code != 10001) {
                this.RTverityInfoImgCode = "图形验证码错误";
                this.getImgCode();
              } else {
                this.RTverityInfoImgCode = "";
                this.getPhoneCode();
              }
            });
        }
      });
    },

    verityCode() {
      if (!this.formData.phone || !this.formData.phoneCode) return;
      axios
        .get(
          this.serveAPI.verityCode +
            this.formData.phone +
            "/" +
            this.formData.phoneCode
        )
        .then(response => {
          if (response.data.error) {
            this.RTverityInfoCoder = "验证码不匹配";
          } else {
            this.RTverityInfoCoder = "";
          }
        });
    },

    //----------------------------------------------------
    // serve

    getImgCode() {
      axios.get(this.serveAPI.getImgCode).then(res => {
        // console.log(res.data.Response.data)
        this.imgCode = {
          img: "data:image/jpeg;base64," + res.data.Response.data,
          code: res.data.Response.code
        };
      });
    },

    getPhoneCode() {
      this.$validator.validate("手机号").then(result => {
        if (result && !this.RTverityInfoPhone) {
          this.$validator.validate("图形验证码").then(result => {
            if (result && !this.RTverityInfoImgCode) {
              axios
                .post(this.serveAPI.getCode, {
                  mobileNumber: this.formData.phone
                })
                .then(() => {
                  alert("已发送");
                  this.getCodeCountTimer(60);
                })
                .catch(err => {
                  alert(JSON.stringify(err));
                  this.senderInfo = "获取失败";
                  this.senderAble = false;
                });
            }
          });
        }
      });
    },

    getInviteList() {
      axios.get(this.serveAPI.inviteList).then(res => {
        // console.log(res);
        if (res.data.object.length > 0) {
          let list = [];
          // res.data.object.split(', ').map(e => {
          //   if (e.match('headImageUrl=')) list.push(e.split('headImageUrl=')[1])
          // })
          res.data.object.map(e => {
            let image = null;
            if (e.headImageUrl) image = e.headImageUrl;
            list.push(image);
          });
          store.commit("upload", { prope: "inviteList", data: list });
        }
      });
    },

    submit() {
      this.cleanState();
      this.verityCode();
      setTimeout(() => {
        this.$validator.validateAll().then(result => {
          if (
            result &&
            !this.RTverityInfoPhone &&
            !this.RTverityInfoCoder &&
            !this.RTverityInfoImgCode
          ) {
            axios
              .post(this.serveAPI.login, {
                mobileNumber: this.formData.phone
              })
              .then(res => {
                if (res.data.error) {
                  alert(JSON.stringify(res.data.error));
                } else {
                  // alert("提交数据接口返回：" + JSON.stringify(res));
                  let calfKey = res.data.object.calfKey;
                  store.commit("upload", { prope: "calfKey", data: calfKey });
                  // this.cookieSet('calfKey', calfKey)
                  // console.log('calfKey in cookie', this.cookieGet('calfKey'))
                  this.loginResult = "";
                  this.getInviteList();
                  // store.commit("upload", { prope: "uid", data: res.data.object });
                  store.commit("upload", { prope: "loginState", data: false });
                  store.commit("upload", { prope: "loginResult", data: true });
                }
              });
          }
        });
      }, 500);
    },

    //----------------------------------------------------
    // getPhoneCode counter
    getCodeCountTimer(e) {
      if (e) this.getCodeCounter = 60;
      this.senderAble = false;
      if (this.getCodeCounter > 0) {
        this.getCodeCount();
      } else {
        this.getCodeCounter = null;
        this.senderAble = true;
      }
    },
    getCodeCount() {
      setTimeout(() => {
        this.getCodeCounter--;
        this.getCodeCountTimer();
      }, 1000);
    },
    //----------------------------------------------------
    // cookie
    cookieGet(key) {
      key = key + "=";
      let cookieList = document.cookie.split(";");
      for (let i = 0; i < cookieList.length; i++) {
        const item = cookieList[i].trim();
        if (item.indexOf(key) == 0)
          return item.substring(key.length, item.length);
      }
      return;
    },
    cookieSet(key, value, day) {
      let d = new Date();
      d.setTime(d.getTime() + day * 24 * 60 * 60 * 1000);
      let expires = "expires=" + d.toGMTString();
      document.cookie = key + "=" + value + ";" + expires;
    }
  },
  mounted() {
    this.init();
  }
};
</script>
<style lang='stylus' scoped>
@import '../../../assets/styles/index.styl'
.login {
  z-index 100
  position fixed
  height 100vh
  width 100vw
  top 0
  left 0
  .texture {
    display inline-block
    position absolute
    top 0
    bottom 0
    left 0
    right 0
    background rgba(0, 0, 0, 0.5)
    z-index 99
  }
  .main {
    position absolute
    z-index 100
    top 45%
    left 50%
    transform translate(-50%, -50%)
    background #fff
    border-radius 5px
    width 80%
    box-shadow 0 1px 3px rgba(26, 26, 26, 0.1)
    .close {
      width 25px
      height 25px
      position absolute
      top 12px
      right 12px
      font-size 24px
      text-align center
      opacity 0.5
      border 1px solid #000
      border-radius 50%
      &:before, &:after {
        content ''
        display inline-block
        width 60%
        height 1px
        background #000
        position absolute
        left 50%
        top 50%
        transform translate(-50%, -50%) rotate(45deg)
      }
      &:after {
        transform translate(-50%, -50%) rotate(-45deg)
      }
    }
    .login-inner {
      padding 15px
      .title {
        text-align center
        h2 {
          font-size 18px
          color #ff423f
          display inline-block
          padding 15px
          background-image url('../../../assets/images/jdj_index_login_tit.jpg')
          background-size contain
          background-repeat no-repeat
          background-position center
        }
      }
      .form {
        .form-inner {
          .input {
            position relative
            margin 10px 0px
            text-align left
            .inner {
              border 1px solid rgba(0, 0, 0, 0.03)
              border-radius 5px
              position relative
              display inline-block
              padding-left 30px
              width 100%
              box-sizing border-box
              label {
                font-size 14px
                display inline-block
                height 16px
                position absolute
                left 8px
                top 50%
                transform translateY(-55%)
                img {
                  vertical-align middle
                  height 100%
                  width auto
                }
              }
              input {
                outline 0
                border 0
                width 100%
                padding 15px 0px 15px 5px
                font-size 14px
                display inline-block
                background rgba(0, 0, 0, 0)
              }
            }
            &:nth-child(2), &:nth-child(3) {
              .inner {
                width 60%
              }
            }
          }
          .imgCode {
            display inline-block
            position relative
            border 1px solid rgba(0, 0, 0, 0.03)
            border-radius 5px
            height 48px
            float right
            width 35%
            padding 8px
            box-sizing border-box
            & i {
              background-size contain
              background-position center
              background-repeat no-repeat
              display inline-block
              height 100%
              width 100%
            }
          }
          .sender {
            display inline-block
            position relative
            border-radius 5px
            height 48px
            line-height 40px
            text-align center
            float right
            width 35%
            padding 5px
            box-sizing border-box
            background c10
            span {
              font-size 13px
              color #fff
            }
            &.disable {
              background #aaa
            }
          }
          .error-info {
            text-align left
            display block
            font-size 12px
            color c5
            padding 5px 0
          }
        }
      }
      .formButton {
        margin 20px 0 15px
        .submit {
          position relative
          text-align center
          padding 12px
          border-radius 50px
          color #fff
          &:before, &:after {
            content ''
            display inline-block
            position absolute
            top 0
            bottom 0
            left 0
            right 0
            background linear-gradient(to left, #ff5d51, #ff893a)
            background #ccc
            z-index 1
            border-radius 3px
            border-radius 50px
            transition transform 0.3s ease
          }
          &:after {
            z-index 0
            background #da271a
            filter blur(5px)
            transform-origin center bottom
            transform scaleX(0.9) scaleY(0.9)
            transform scaleX(0.9) scaleY(0.5)
            opacity 0.8
            opacity 0
          }
          span {
            position relative
            z-index 2
            font-size 18px
          }
          &.act {
            &:before {
              background linear-gradient(-45deg, #ff5d51, #ff893a)
            }
            &:after {
              opacity 0.8
              transform scaleX(0.9) scaleY(0.9)
            }
          }
          &.back {
            margin-top 15px
            border 1px solid c6
            color c6
            &:before, &:after {
              display none
            }
          }
        }
        .subInfo {
          margin-top 15px
          font-size 12px
          color #c1a396
          opacity 0.7
          text-align center
        }
      }
    }
    .tips {
      text-align center
      .info {
        padding 15px
        opacity 0.7
      }
      .button {
        border-top 1px solid rgba(0, 0, 0, 0.1)
        padding 15px 0
        color c2
      }
    }
  }
  .pop {
    display none
    position absolute
    top 40%
    left 50%
    transform translate(-50%, -50%)
    background rgba(0, 0, 0, 0.7)
    padding 15px
    z-index 101
    // width 50%
    font-size 14px
    text-align center
    border-radius 5px
    span {
      color #fff
      white-space nowrap
    }
    &.act {
      display block
    }
  }
}
</style>
